<template>
  <div class="create-message">
    <h2 style="font-weight: bold; font-size: 24px; color: #4CAF50;">
      <i class="fas"></i> 创建阅后即焚消息
    </h2>
    <div class="message-form">
      <div class="form-group">
        <textarea 
          v-model="content"
          placeholder="输入消息内容"
          rows="5"
        ></textarea>
      </div>

      <div class="image-upload">
        <input 
          type="file" 
          @change="handleImageUpload" 
          accept="image/*"
          ref="fileInput"
          style="display: none"
        >
        <button @click="$refs.fileInput.click()" class="upload-btn">
          选择图片
        </button>
        <span v-if="imagePreview" class="file-name">已选择图片</span>
      </div>

      <div v-if="imagePreview" class="image-preview">
        <img :src="imagePreview" alt="预览图片">
        <button @click="removeImage" class="remove-btn">删除图片</button>
      </div>

      <div class="password-section">
        <label class="checkbox-label">
          <input type="checkbox" v-model="usePassword">
          启用密码保护
        </label>
        
        <div v-if="usePassword" class="password-input">
          <input 
            type="password" 
            v-model="password"
            placeholder="输入访问密码"
          >
        </div>
        <div class="form-group">
          <input 
            type="text" 
            v-model="title"
            placeholder="页面标题（可选，默认为：阅后即焚消息）"
            class="title-input"
          >
        </div>
      </div>

      <button @click="createMessage" :disabled="isLoading" class="create-btn">
        创建消息
      </button>

      <div v-if="showLoadingAlert" class="alert-message">
        {{ loadingMessage }}
      </div>

      <div v-if="messageUrl" class="message-url">
        <p style="font-weight: bold; color: green;">消息已创建成功！以下是访问链接：</p>
        <input type="text" readonly :value="messageUrl" ref="urlInput" class="link-input">
        <button @click="copyUrl">复制链接</button>
      </div>

      <div v-if="showAlert" class="alert-message">
        {{ alertMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import axios from 'axios'
import imageCompression from 'browser-image-compression';
import { config } from '../config';

export default {
  name: 'CreateMessage',
  setup() {
    const content = ref('')
    const title = ref('')
    const messageUrl = ref('')
    const urlInput = ref(null)
    const imageFile = ref(null)
    const imagePreview = ref(null)
    const fileInput = ref(null)
    const usePassword = ref(false)
    const password = ref('')
    const isLoading = ref(false)
    const progress = ref(0)
    const alertMessage = ref('');
    const showAlert = ref(false);
    const loadingMessage = ref('消息创建中...');
    const showLoadingAlert = ref(false);

    const isValid = computed(() => {
      return content.value.trim() !== '' || imageFile.value !== null;
    })

    const handleImageUpload = async (event) => {
      const file = event.target.files[0];
      if (file) {
        if (file.size > 16 * 1024 * 1024) { // 16MB限制
          alert('图片大小不能超过16MB');
          return;
        }
        // 压缩图片
        const options = {
          maxSizeMB: 1,
          maxWidthOrHeight: 800,
          useWebWorker: true,
        };
        try {
          const compressedFile = await imageCompression(file, options);
          imageFile.value = compressedFile;
          const reader = new FileReader();
          reader.onload = (e) => {
            imagePreview.value = e.target.result;
          };
          reader.readAsDataURL(compressedFile);
          // 确保 imageFile 更新
          imageFile.value = compressedFile;
        } catch (error) {
          console.error('图片压缩失败:', error);
          alert('图片压缩失败');
        }
      }
    }

    const removeImage = () => {
      imageFile.value = null
      imagePreview.value = null
      if (fileInput.value) {
        fileInput.value.value = ''
      }
    }

    const createMessage = async () => {
      if (!content.value.trim() && !imageFile.value) {
        alertMessage.value = '请输入消息内容或上传图片';
        showAlert.value = true;
        setTimeout(() => { showAlert.value = false; }, 3000); // 3秒后自动隐藏
        return;
      }
      showLoadingAlert.value = true;
      messageUrl.value = '';
      try {
        const messageData = {
          content: content.value,
          title: title.value,
          image: imagePreview.value,
          imageType: imageFile.value?.type,
          hasPassword: usePassword.value,
          password: usePassword.value ? password.value : null
        }

        console.log('Backend API URL:', config.BACKEND_API_URL);
        const response = await axios.post(config.BACKEND_API_URL, messageData, {
          onUploadProgress: (progressEvent) => {
            const total = progressEvent.total;
            const current = progressEvent.loaded;
            progress.value = (current / total) * 100;
          }
        });
        const accessKey = response.data.accessKey;
        messageUrl.value = `${window.location.origin}/read/${accessKey}`;
        content.value = '';
        title.value = '';
        password.value = '';
        usePassword.value = false;
        removeImage();
      } catch (error) {
        console.error('Error creating message:', error);
        if (error.response?.data?.message) {
          alert(error.response.data.message);
        } else {
          alert('创建消息失败，请稍后重试');
        }
      } finally {
        showLoadingAlert.value = false;
      }
    }

    const copyUrl = () => {
      console.log('Clipboard API:', navigator.clipboard);
      if(!navigator.clipboard) {
        urlInput.value.select()
        document.execCommand('copy')
      } else {
        navigator.clipboard.writeText(messageUrl.value);
      }
      //navigator.clipboard.writeText(messageUrl.value);
      // 设置弹出框内容并显示
      alertMessage.value = '链接已复制！';
      showAlert.value = true;
      setTimeout(() => { showAlert.value = false; }, 3000); // 3秒后自动隐藏
    };

    return {
      content,
      title,
      messageUrl,
      urlInput,
      createMessage,
      copyUrl,
      handleImageUpload,
      imagePreview,
      removeImage,
      isValid,
      fileInput,
      usePassword,
      password,
      isLoading,
      progress,
      alertMessage,
      showAlert,
      loadingMessage,
      showLoadingAlert
    }
  }
}
</script>

<style scoped>
.create-message {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.message-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.title-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1.1em;
}

textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 120px;
}

.image-upload {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-btn {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.file-name {
  color: #666;
}

.image-preview {
  position: relative;
  max-width: 300px;
  margin: 10px 0;
}

.image-preview img {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

.remove-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 5px 10px;
  background-color: rgba(255, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.create-btn {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.message-url {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.message-url input {
  width: 100%;
  padding: 8px;
  margin: 10px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.message-url button {
  padding: 8px 16px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.link-input {
  color: blue;
}

.password-section {
  margin: 15px 0;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.password-input {
  margin-top: 10px;
}

.password-input input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.alert-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}
</style>
